package com.video.controller;


import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.video.common.lang.Result;
import com.video.entity.Blog;
import com.video.service.BlogService;
import com.video.util.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;


/**
 * @author maomao
 */
@RestController
public class BlogController {

    @Resource
    private BlogService blogService;

    @GetMapping("/blogs")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage) {

        Page<Blog> page = new Page<>(currentPage, 5);

        Page<Blog> pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created"));
        return Result.success(pageData);
    }

    @GetMapping("/blog/{id}")
    public Result detail(@PathVariable(name = "id") Long id) {
        Blog blog = blogService.getById(id);

        Assert.notNull(blog, "文章已经被删除");
        return Result.success(blog);
    }

    @PostMapping("/blog/delete/{id}")
    public Result delete(@PathVariable(name = "id") Long id){
        Blog blog = blogService.getById(id);

        Assert.notNull(blog, "文章已经被删除");

        Assert.isTrue(blog.getUserId().longValue() == ShiroUtils.getProfile().getId().longValue(), "没有权限删除");

        blogService.removeById(id);

        return Result.success(null);
    }

    @RequiresAuthentication
    @PostMapping("/blog/edit")
    public Result edit(@Validated @RequestBody Blog blog) {

        Blog temp;

        if (blog.getId() != null) {
            temp = blogService.getById(blog.getId());
            Assert.isTrue(temp.getUserId().longValue() == ShiroUtils.getProfile().getId().longValue(), "没有权限编辑");

        } else {
            temp = new Blog();
            temp.setUserId(ShiroUtils.getProfile().getId());
            temp.setCreated(LocalDateTime.now());
            temp.setStatus(0);
        }

        BeanUtils.copyProperties(blog, temp, "id", "userId", "created", "status");

        blogService.saveOrUpdate(temp);

        return Result.success(null);
    }
}
